package com.jrx.anytxn.transaction.job.paph.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlServiceFeeLog;
import com.jrx.anytxn.transaction.bean.PaphFileBean;
import com.jrx.anytxn.transaction.job.paph.step.GenerateServiceFeeListener;
import com.jrx.anytxn.transaction.job.paph.step.GenerateServiceFeeProcessor;
import com.jrx.anytxn.transaction.job.paph.step.GenerateServiceFeeWriter;
import com.jrx.anytxn.transaction.service.IPaphFileService;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张靖烽
 * @name GenerateServiceFeeConfiguration
 * @description 生成技术服务费同步分库文件批量
 * @create 2021-03-12 15:53
 **/
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class GenerateServiceFeeConfiguration {

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private GenerateServiceFeeListener generateServiceFeeListener;
    @Autowired
    private GenerateServiceFeeProcessor generateServiceFeeProcessor;
    @Autowired
    private GenerateServiceFeeWriter generateServiceFeeWriter;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IPaphFileService paphFileService;
    @Autowired
    private PaphFileConfig paphFileConfig;

    @Bean
    public Job generateServiceFeeJob() {
        return jobBuilderFactory.get("generateServiceFeeJob")
                .start(generateServiceFeeStep())
                .build();
    }

    @Bean
    public Step generateServiceFeeStep() {
        return stepBuilderFactory.get("generateServiceFeeStep")
                .listener(generateServiceFeeListener)
                .<TlServiceFeeLog, PaphFileBean>chunk(anytxnBatchProperties.getServiceFeeFileConfig().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(reader())
                .processor(generateServiceFeeProcessor)
                .writer(generateServiceFeeWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getServiceFeeFileConfig().getThrottleLimit())//多线程
                .build();
    }

    @Bean
    @StepScope
    public MyBatisPagingItemReader<TlServiceFeeLog> reader() {
        MyBatisPagingItemReader<TlServiceFeeLog> pagingItemReader = new MyBatisPagingItemReader<>();
        pagingItemReader.setSaveState(false);
        pagingItemReader.setSqlSessionFactory(sqlSessionFactory);
        pagingItemReader.setPageSize(anytxnBatchProperties.getServiceFeeFileConfig().getPageSize());
        pagingItemReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtTlServiceFeeLogMapper.selectLastMonthServiceFee");
        Map<String, Object> map = new HashMap<>(1);
        // 获取当前业务日期
        PrOrganizationTable organization = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
        String businessDate = DateFormatUtils.format(organization.getToday(), DateUtils.DATE_PATTERN);
        // 获取上一月
        String date = DateTime.parse(businessDate).plusMonths(-1).toString("yyyyMM");
        map.put("tradeMonth", date);
        pagingItemReader.setParameterValues(map);
        return pagingItemReader;
    }

}
